package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.domain.Favorite;
import com.example.domain.Movie;
import com.example.domain.model.MovieDTO;
import com.example.domain.model.SearchDTO;
import com.example.mapper.MovieMapper;
import com.example.service.FavoriteService;
import com.example.mapper.FavoriteMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author Administrator
* @description 针对表【favorite】的数据库操作Service实现
* @createDate 2023-03-20 09:44:27
*/
@Service
public class FavoriteServiceImpl extends ServiceImpl<FavoriteMapper, Favorite> implements FavoriteService{

    @Autowired
    private FavoriteMapper favoriteMapper;

    @Autowired
    private MovieMapper movieMapper;

    @Override
    public Favorite getById(String id,String userId) {
        return favoriteMapper.selectOne(new LambdaQueryWrapper<Favorite>()
                .eq(Favorite::getMovieId,id)
                .eq(Favorite::getUserId,userId));
    }

    @Override
    public IPage<MovieDTO> getList(String userId, Page<Favorite> page, SearchDTO searchDTO) {
        page.setOptimizeCountSql(false);
        List<String> list = favoriteMapper.selectList(new LambdaQueryWrapper<Favorite>()
                .eq(Favorite::getUserId, userId))
                .stream().map(Favorite::getMovieId)
                .collect(Collectors.toList());
        return movieMapper.selectPageList(page,list,searchDTO.getSearchKeyword());
    }

    @Override
    public boolean save(String movieId,String userId) {
        Favorite favorite = new Favorite();
        favorite.setMovieId(movieId);
        favorite.setUserId(userId);
        return favoriteMapper.insert(favorite) > 0;
    }

    @Override
    public boolean update(String id, Favorite favorite) {
        Favorite f = favoriteMapper.selectById(id);
        if (f != null){
            favorite.setId(id);
            return favoriteMapper.updateById(favorite) > 0;
        }else {
            return false;
        }

    }

    @Override
    public boolean delete(String movieId,String userId) {

        return favoriteMapper.delete(new LambdaQueryWrapper<Favorite>()
                .eq(Favorite::getMovieId,movieId)
                .eq(Favorite::getUserId,userId)) > 0;
    }
}




